package com.hxd.otc.module.my.activity;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.dialog.ShareLinkDialog;
import com.hxd.otc.module.my.contract.DownloadPosterContract;
import com.hxd.otc.module.my.presenter.DownloadPosterPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.AddressUtil;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.TitleBar;
import com.hxd.otc.widget.WalletDialogTipsUtil;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.lang.ref.SoftReference;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lzy on 2018/12/20 0020.
 * description ${下载海报}
 */
public class DownloadPosterActivity extends PermissionActivity<DownloadPosterPresenter> implements DownloadPosterContract.IView {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.iv_poster_bg)
    ImageView mIvPosterBg;
    @BindView(R.id.iv_poster)
    ImageView mIvPoster;
    @BindView(R.id.tv_save_to_local)
    TextView mTvSaveToLocal;
    @BindView(R.id.tv_save_and_share)
    TextView mTvSaveAndShare;

    private ShareLinkDialog mShareLinkDialog;

    private static String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private SoftReference<Handler> mHandlerSoftReference;
    private SoftReference<Bitmap> mQrBitmapReference;
    private SoftReference<Bitmap> mPosterBitmapReference;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_download_poster;
    }

    @Override
    protected DownloadPosterPresenter createPresenter() {
        return new DownloadPosterPresenter(this);
    }

    @Override
    protected void initView() {
        mIvPoster.setImageBitmap(getQrBitmap());
    }

    private Bitmap getQrBitmap() {
        if (mQrBitmapReference == null || mQrBitmapReference.get() == null) {
            mQrBitmapReference = new SoftReference<>(CodeUtils.createImage(UserHelper.getRecommendedAddress(), DensityUtil.dp2px(120), DensityUtil.dp2px(120), null));
        }
        return mQrBitmapReference.get();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {

    }

    @OnClick({R.id.tv_save_to_local, R.id.tv_save_and_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_save_to_local:
                checkPermission(false);
                break;
            case R.id.tv_save_and_share:
                checkPermission(true);
                break;
        }
    }


    private void checkPermission(final boolean isShare) {
        super.requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                if (permissions.length == allowPermissions.size()) {
                    onCreateDownloadPoster(isShare);
                }
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                WalletDialogTipsUtil.showExternalTipsDialog(DownloadPosterActivity.this);
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                WalletDialogTipsUtil.showExternalTipsDialog(DownloadPosterActivity.this);
            }

            @Override
            public void onLowVersion() {
                onCreateDownloadPoster(isShare);
            }
        }, permissions);
    }

    private void onCreateDownloadPoster(final boolean isShare) {
        if (mHandlerSoftReference == null || mHandlerSoftReference.get() == null) {
            mHandlerSoftReference = new SoftReference<>(new Handler());
        }
        mHandlerSoftReference.get().post(new Runnable() {
            @Override
            public void run() {
                viewSaveToImage(isShare);
            }
        });

    }

    private void viewSaveToImage(final boolean isShare) {
        onShowLoading();
        if (mPosterBitmapReference == null || mPosterBitmapReference.get() == null) {
            mPosterBitmapReference = new SoftReference<>(createSaveQRBitmap(getQrBitmap()));
        }
        AddressUtil.saveAddress(mPosterBitmapReference.get(), "downloadPoster_" + UserHelper.getInviteCode(),
                new AddressUtil.SaveAddressListener() {
                    @Override
                    public void fail(String str) {
                        onHideLoading();
                        showToast(str);
                    }

                    @Override
                    public void success(String str) {
                        onHideLoading();
                        if (isShare) {
                            openShareLinkDialog();
                        } else {
                            showToast(getString(R.string.save_success));
                        }
                    }
                });
    }

    /**
     * 保存二维码图片
     */
    private Bitmap createSaveQRBitmap(Bitmap qrBitmap) {
        int width = DataUtils.dp2px(this, 225);     // 屏幕宽度（像素）
        int height = DataUtils.dp2px(this, 360);   // 屏幕高度（像素）
        View view = LayoutInflater.from(this).inflate(R.layout.layout_download_poster, null, false);
        // 整个View的大小 参数是左上角 和右下角的坐标
        view.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        /** 当然，measure完后，并不会实际改变View的尺寸，需要调用View.layout方法去进行布局。
         * 按示例调用layout函数后，View的大小将会变成你想要设置成的大小。
         */
        view.measure(measuredWidth, measuredHeight);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        ImageView qr = view.findViewById(R.id.iv_poster);
        qr.setImageBitmap(qrBitmap);
        return loadBitmapFromView(view);
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

    private void openShareLinkDialog() {
        if (mShareLinkDialog == null) {
            mShareLinkDialog = new ShareLinkDialog(this)
                    .setTitle(getString(R.string.save_success))
                    .setConfirmText(getString(R.string.lets_go_to_wechat_and_share_that))
                    .isShowContent(false)
                    .isShowCopySuccessIcon(false)
                    .isShowLink(false);
        }
        mShareLinkDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(mShareLinkDialog);
    }

}
